package com.sn.author.service.impl;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author xiaom
 * @Date 2020/9/25 15:50
 * @Version 1.0.0
 * @Description <>
 **/
@ServerEndpoint(value = "/message")
@Component
@Slf4j
public class WebSocket {

    private static CopyOnWriteArrayList<WebSocket> webSocketSet = new CopyOnWriteArrayList<>();//泛型就是当前类

    @Getter
    public Session session;

    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSocketSet.add(this);
        try {
            log.info("链接成功.......");
            sendMessage("{}");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendMessage(String message) throws IOException {
        if(webSocketSet.isEmpty()){
            log.error("无socket连接可用");
            return;
        }
        log.info("推送消息：{}",message );
        webSocketSet.get(webSocketSet.size()-1).session.getBasicRemote().sendText(message);
    }

    @OnClose
    public void onClose() {
        log.info("连接关闭");
    }


    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        log.info("来自客户端的消息:" + message);
        sendMessage(message);
    }
}
